//
//  YKGTSDK.m
//  YKGTSDK
//
//  Created by edward on 2023/3/6.
//

#import "YKGTSDK.h"
#import <GTSDK/GeTuiSdk.h>


@interface YKGTSDK () <GeTuiSdkDelegate>
///
@property (nonatomic, weak, readwrite) id<YKGTSDKConflictDelegate> conflictDelegate;
///
@property (nonatomic, weak, readwrite) id<YKGTSDKDelegate> delegate;
///
@property (nonatomic, assign, readwrite) SdkStatus status;


@end

@implementation YKGTSDK

static YKGTSDK *_instance;

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });

    return _instance;
}

+ (instancetype)shared
{
    if (_instance == nil) {
        _instance = [[YKGTSDK alloc] init];
        _instance.status = [GeTuiSdk status];
    }

    return _instance;
}

+ (void)configConflictDelegate:(id<YKGTSDKConflictDelegate>)conflictDelegate
{
    [YKGTSDK shared].conflictDelegate = conflictDelegate;
}

+ (void)confitDelegate:(id<YKGTSDKDelegate>)delegate
{
    [YKGTSDK shared].delegate = delegate;
}

+ (void)registWithAppId:(NSString *)appid appKey:(NSString *)appKey appSecret:(NSString *)appSecret launchingOptions:(NSDictionary * __nullable)launchOptions
{
    dispatch_async(dispatch_get_main_queue(), ^{
        // 通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注：该方法需要在主线程中调用
        [GeTuiSdk startSdkWithAppId:appid appKey:appKey appSecret:appSecret delegate:[YKGTSDK shared] launchingOptions:launchOptions];
    });
    
}

//MARK: get/set

- (void)setConflictDelegate:(id<YKGTSDKConflictDelegate>)conflictDelegate
{
    if (!_conflictDelegate) {
        _conflictDelegate = conflictDelegate;
        if ([_conflictDelegate respondsToSelector:@selector(registerRemoteNotification)]) {
            UNAuthorizationOptions options = [_conflictDelegate registerRemoteNotification];
            [GeTuiSdk registerRemoteNotification:options];
        }
    }else {
        
#ifdef DEBUG
        NSLog(@"已注册 YKGTSDKConflictDelegate");
#endif
    }
}

- (void)setDelegate:(id<YKGTSDKDelegate>)delegate
{
    if (!_delegate) {
        _delegate = delegate;
    }else {
        
#ifdef DEBUG
        NSLog(@"已注册 YKGTSDKDelegate");
#endif
    }
}


//MARK: GeTuiSdkDelegate

/// SDK运行状态通知
/// @param status 返回SDK运行状态
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)status
{
    self.status = status;
}


/// SDK登入成功返回clientId
/// @param clientId 标识用户的clientId
/// @warning 启动GeTuiSdk后，SDK会自动向个推服务器注册SDK，当成功注册时，SDK通知应用注册成功。
/// @warning 注册成功仅表示推送通道建立，如果appid/appkey/appSecret等验证不通过，依然无法接收到推送消息，请确保验证信息正确。
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId
{
    if (self.conflictDelegate && [self.conflictDelegate respondsToSelector:@selector(didRegisterClient:)]) {
        [self.conflictDelegate didRegisterClient:clientId];
    }
    
#ifdef DEBUG
    NSLog(@"个推注册成功 clientId:%@",clientId);
#endif
}

/// 通知授权结果（iOS10及以上版本）
/// @param granted 用户是否允许通知
/// @param error 错误信息
- (void)GetuiSdkGrantAuthorization:(BOOL)granted error:(NSError *)error
{
    
}

/// 收到通知信息
/// @param userInfo apns通知内容
/// @param center UNUserNotificationCenter（iOS10及以上版本）
/// @param response UNNotificationResponse（iOS10及以上版本）
/// @param completionHandler 用来在后台状态下进行操作（iOS10以下版本）
- (void)GeTuiSdkDidReceiveNotification:(NSDictionary *)userInfo notificationCenter:(UNUserNotificationCenter *)center response:(UNNotificationResponse *)response fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(didReceiveNotification:)]) {
        [self.delegate didReceiveNotification:userInfo];
    }
    
    if (completionHandler) {
        completionHandler(UIBackgroundFetchResultNoData);
    }
}

/// 收到透传消息
/// @param userInfo    推送消息内容,  {"payload": 消息内容}
/// @param fromGetui   YES: 个推通道  NO：苹果apns通道
/// @param offLine     是否是离线消息，YES.是离线消息
/// @param appId       应用的appId
/// @param taskId      推送消息的任务id
/// @param msgId       推送消息的messageid
/// @param completionHandler 用来在后台状态下进行操作（通过苹果apns通道的消息 才有此参数值）
- (void)GeTuiSdkDidReceiveSlience:(NSDictionary *)userInfo fromGetui:(BOOL)fromGetui offLine:(BOOL)offLine appId:(NSString *)appId taskId:(NSString *)taskId msgId:(NSString *)msgId fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(didReceiveSlience:fromGetui:offLine:appId:taskId:msgId:)]) {
        [self.delegate didReceiveSlience:userInfo fromGetui:fromGetui offLine:offLine appId:appId taskId:taskId msgId:msgId];
    }
    
    if (completionHandler) {
        completionHandler(UIBackgroundFetchResultNoData);
    }
}

- (void)GeTuiSdkNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification completionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    UNNotificationPresentationOptions option = UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound;
    if (self.conflictDelegate && [self.conflictDelegate respondsToSelector:@selector(getNotificationCenter:willPresentNotification:)]) {
        option = [self.conflictDelegate getNotificationCenter:center willPresentNotification:notification];
    }
    completionHandler(option);
}

@end
